package top.sky.log.listener;

import top.sky.log.config.LogConstant;
import org.slf4j.MDC;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * MDC listener.
 * <p>Implementations of {@link ServletRequestListener } interface are invoked at their
 * {@link #requestInitialized} method in the order in which they have been
 * declared, and at their {@link #requestDestroyed} method in reverse
 * order.
 *
 * @author shijin.liu
 * @since 2023-07-01
 */
public class MDCListener implements ServletRequestListener {


    /**
     * The request is about to come into scope of the web application.
     * The default implementation is a NO-OP.
     *
     * @param requestEvent Information about the request
     */
    @Override
    public void requestInitialized(ServletRequestEvent requestEvent) {
        HttpServletRequest req = (HttpServletRequest) requestEvent.getServletRequest();
        String transactionId = req.getHeader(LogConstant.HTTP_HEADER_ATTRIBUTE_TRANSACTION_ID);
        if (Objects.nonNull(transactionId)) {
            MDC.put(LogConstant.MDC_KEY_TRANSACTION_ID, transactionId);
        }
    }

    /**
     * Remove cache of locations in {@link ThreadLocal} .
     *
     * @param requestEvent The {@link ServletRequestEvent} request event.
     */
    @Override
    public void requestDestroyed(ServletRequestEvent requestEvent) {
        String transactionId = MDC.get(LogConstant.MDC_KEY_TRANSACTION_ID);
        if (Objects.nonNull(transactionId)) {
            MDC.remove(transactionId);
        }
    }
}
